from flask import Flask
from tools.dbhelper import DBHelper

# 实例化DBHelper类
db = DBHelper()


def create_app():
    """
    创建 FLask 应用
    :return:
    """
    app = Flask(__name__, static_folder=None)
    from api import employee as bp_employee
    # 注册蓝图
    app.register_blueprint(bp_employee, url_prefix='/employee')
    return app


def reset():
    """
    刷新数据源，方便每一次增加、修改、删除完之后刷新
    :return:
    """
    with db.cursor() as cursor:
        sql = """SELECT * FROM employee;"""
        results = db.queryAll(cursor, sql)
    return results


def select_employee_first(uid):
    """
    查询一条员工信息
    :param uid:
    :return:
    """
    with db.cursor() as cursor:
        sql = f"""SELECT *
                    FROM employee
                        WHERE uid={uid};"""
        result = db.queryAll(cursor, sql)
        employee = result[0]
        return employee


def insert_employee(uname, upwd, truename, birth, salary, mobile):
    """
    添加员工信息
    :param uname:
    :param upwd:
    :param truename:
    :param birth:
    :param salary:
    :param mobile:
    :return:
    """
    with db.cursor() as cursor:
        sql = """INSERT INTO employee(uname, upwd, truename, birth, salary, mobile) 
        VALUES ('{}', '{}', '{}', '{}', '{}', '{}');""".format(uname, upwd, truename, birth, salary, mobile)
        rows = db.execute(cursor, sql)
        if rows > 0:
            print('添加员工信息成功')
            return True
        else:
            print('添加员工信息失败')
            return False


def update_employee(uid, uname, upwd, truename, birth, salary, mobile):
    """
     修改员工信息
    :param uname:
    :param upwd:
    :param truename:
    :param birth:
    :param salary:
    :param mobile:
    :return:
    """
    # 执行sql
    with db.cursor() as cursor:
        sql = """UPDATE employee
                    SET uname='{}', upwd='{}', truename='{}', birth='{}', salary='{}', mobile='{}'
                        WHERE uid={};""".format(uname, upwd, truename, birth, salary, mobile, uid)
        rows = db.execute(cursor, sql)
        if rows > 0:
            print('修改员工信息成功')
            return True
        else:
            print('修改员工信息失败')
            return False


def delete_employee(uid):
    """
    删除员工信息
    :param uid:
    :return:
    """
    with db.cursor() as cursor:
        sql = f"""DELETE FROM employee
                    WHERE uid={uid};"""
        rows = db.execute(cursor, sql)
        if rows > 0:
            print('删除员工信息成功')
            return True
        else:
            print('删除员工信息失败')
            return False
